import xlwings as xw
import time


class ExcelTest:
    def __init__(self):
        self.file = ''

    def importFile(self):
        app = xw.App(visible=True, add_book=False)

        wb = app.books.open('./a.xlsx')

        # 打印当前活跃的books-<Book [b.xlsx]>
        print(app.books.active)
        # 选择
        sht = wb.sheets['sheet1']
        sht.range("A1").value = "A1"
        # 行写入
        sht.range("A2").value = [1, 2]
        # 列写入
        sht.range("B1").options(transpose=True).value = [3, 4]

        # 写入表数据
        sht.range('A4').options(expand='table').value = [[1, 2, 3], [3, 4, 5], [3, 4, 5], [3, 4, 5]]

        # 打印当前的book-Books([<Book [a.xlsx]>, <Book [b.xlsx]>])
        print(app.books)

        wb.save()

        # 关闭a.xlsx文件-指定操作的excel
        # wb.close()
        app.books[0].close()

        # time.sleep(1)
        app.quit()

    def newFile(self):
        app = xw.App(visible=True, add_book=False)

        # 添加一个新的工作薄
        wb = app.books.add()

        # 保存文件
        wb.save('./a2.xlsx')
        wb.close()
        app.quit()

    def exportData(self):
        app = xw.App(visible=True, add_book=False)

        wb = app.books.open('./a.xlsx')
        sht = wb.sheets['sheet1']
        # A1 第一行一列的值
        print(sht.range('a1').value)
        # 以A1为扩展的全部数据
        print(sht.range('a1').expand().value)
        wb.save()
        app.books[0].close()
        app.quit()


if __name__ == "__main__":
    excelTest = ExcelTest()
    #excelTest.importFile()
    # excelTest.newFile()
    excelTest.exportData()
